import { createStyles, LinearProgress, Theme, Typography } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import qs from 'qs';
import React, { useEffect, useState } from 'react';
import Slider, { Settings as SliderSettings } from 'react-slick';
import 'slick-carousel/slick/slick-theme.css';
import 'slick-carousel/slick/slick.css';
import { useSettings } from '../context';
import { ListItemType } from '../pages/Home';
import { apiUrl } from '../util';

const slideSpeed = 500;

const settings: SliderSettings = {
  dots: false,
  infinite: true,
  speed: slideSpeed,
  slidesToShow: 1,
  slidesToScroll: 1,
};

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    appBar: {
      marginBottom: theme.spacing(2),
    },
    title: {
      marginLeft: theme.spacing(2),
      flex: 1,
    },
  }),
);

interface VirtualizedSliderProps {
  directory: string;
  list: ListItemType[];
  index?: number;
}

const VirtualizedSlider: React.FC<VirtualizedSliderProps> = (props) => {
  const {
    directory,
    list,
    index = 0,
  } = props;
  // const classes = useStyles();
  const { rtl } = useSettings();
  // const history = useHistory();
  // const [showAppBar, setShowAppBar] = useState(true);
  const [listIndex, setListIndex] = useState(index);
  const [imageSources, setImageSources] = useState<string[]>([]);

  const convertImageSource = (i: number) => {
    return `${apiUrl}/image?${qs.stringify({
      directory: directory,
      name: list[i].name,
    })}`;
  };

  useEffect(() => {
    if (list?.length === 0) {
      return;
    }

    const images = new Array(5);
    if (index >= 2) {
      for (let i = index - 2; i < Math.min(list.length, index + 3); i++) {
        images[i % 5] = convertImageSource(i);
      }
      if (index + 2 >= list.length) {
        for (let i = Math.max(0, list.length - 5); i < index - 2; i++) {
          images[i % 5] = convertImageSource(i);
        }
      }
    } else {
      for (let i = 0; i < Math.min(list.length, 5); i++) {
        images[i] = convertImageSource(i);
      }
    }
    setImageSources(images);
  }, [list]);

  const beforeSliderChange: SliderSettings['beforeChange'] = (currentSlide, nextSlide) => {
    if (list.length <= 5) {
      return;
    }

    // 判断滑动方向
    let isRight = (currentSlide + 1) % 5 === nextSlide;
    if (rtl) {
      isRight = !isRight;
      currentSlide = 4 - currentSlide;
      nextSlide = 4 - nextSlide;
    }

    if (isRight) {
      // 往右划
      if (listIndex >= 2 && listIndex + 3 < list.length) {
        const images = [...imageSources];
        images[(currentSlide + 3) % images.length] = convertImageSource(listIndex + 3);
        setTimeout(() => setImageSources(images), slideSpeed);
      }
      setListIndex(listIndex + 1);
    } else {
      // 往左划
      if (listIndex - 3 >= 0) {
        const images = [...imageSources];
        images[(currentSlide - 3 + images.length) % images.length] = convertImageSource(listIndex - 3);
        setTimeout(() => setImageSources(images), slideSpeed);
      }
      setListIndex(listIndex - 1);
    }
  };

  return <div>
    {/*<Slide appear={false} in={showAppBar}>*/}
    {/*  <AppBar position={'static'} className={classes.appBar}>*/}
    {/*    <Toolbar>*/}
    {/*      <IconButton edge={'start'} color={'inherit'} onClick={() => history.goBack()}>*/}
    {/*        <ArrowBackIosIcon/>*/}
    {/*      </IconButton>*/}
    {/*    </Toolbar>*/}
    {/*  </AppBar>*/}
    {/*</Slide>*/}

    <Slider
      {...settings}
      rtl={rtl}
      initialSlide={index % 5}
      beforeChange={beforeSliderChange}
    >
      {[...new Array(5)].map((_, i) => (
        <div key={i} data-index={i}>
          <img
            src={imageSources[i]}
            alt={list[i]?.name}
            style={{
              width: '100%',
              height: '100%',
              objectFit: 'cover',
            }}
          />
        </div>
      ))}
    </Slider>

    <Typography variant={'caption'} display={'block'} align={'center'}>
      {list[listIndex]?.name}
    </Typography>

    <br/>
    <LinearProgress variant={'determinate'} value={(listIndex + 1) / (list.length) * 100}/>
    <Typography variant={'caption'} display={'block'} align={'center'}>
      {listIndex + 1} / {list.length}
    </Typography>
  </div>;
};

export default VirtualizedSlider;
